#import "PhoneVerifyPlugin.h"
//#if __has_include(<phone_verify_plugin/phone_verify_plugin-Swift.h>)
//#import <phone_verify_plugin/phone_verify_plugin-Swift.h>
//#else
// Support project import fallback if the generated compatibility header
// is not copied when this plugin is created as a library.
// https://forums.swift.org/t/swift-static-libraries-dont-copy-generated-objective-c-header/19816
//#import "phone_verify_plugin-Swift.h"
//#endif

#import <ATAuthSDK/ATAuthSDK.h>
#import <UIKit/UIKit.h>
#import "PNSBuildModelUtils.h"

#define _CHANNEL_NAME "gitee.com/influency/phone_verify_plugin"

#define METHOD_INIT_SDK "initSdk"
#define METHOD_CHECK_ENV "checkEnv"
#define METHOD_SET_PRIVACY "setPrivacy"
#define METHOD_LOGIN "login"
#define METHOD_QUIT_LOGIN "quitLogin"

#define PARAM_AUTH_KEY "authKey"
#define PARAM_PRIVACY_ISSUE_NAME "privacyIssueName"
#define PARAM_PRIVACY_ISSUE_URL "privacyIssueUrl"
#define PARAM_USER_ISSUE_NAME "userIssueName"
#define PARAM_USER_ISSUE_URL "userIssueUrl"


#define INVOKE_METHOD_ISP "serverProvider"
#define INVOKE_METHOD_LOGIN_TOKEN "loginToken"
#define INVOKE_METHOD_ON_CLICK "onClick"

@implementation PhoneVerifyPlugin
FlutterMethodChannel* methodChannel;
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
//  [SwiftPhoneVerifyPlugin registerWithRegistrar:registrar];
    PhoneVerifyPlugin* plugin = [[PhoneVerifyPlugin alloc] init];
    methodChannel = [FlutterMethodChannel methodChannelWithName:@_CHANNEL_NAME binaryMessenger:[registrar messenger] codec:FlutterJSONMethodCodec.sharedInstance ];
    [registrar addMethodCallDelegate:plugin channel:methodChannel];
    
}

- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result{
//    [SwiftPhoneVerifyPlugin handleMethodCall:call, result:result];
    if([@METHOD_INIT_SDK isEqualToString: call.method]){
//        [self initMethodChannel:call];
        [self handleInitSdk:call result:result];
    }
    else if([@METHOD_CHECK_ENV isEqualToString: call.method]){
//        [self initMethodChannel:call];
        [self handleCheckEnv:call result:result];
    }
    else if([@METHOD_SET_PRIVACY isEqualToString: call.method]){
        //        [self initMethodChannel:call];
        [self handleSetPrivacy:call result:result];
    }
    else if([@METHOD_LOGIN isEqualToString: call.method] ){
        [self handleLogin:call result:result];
    }
    else if([@METHOD_QUIT_LOGIN isEqualToString: call.method] ){
        [self handleQuit:call result:result];
//        [methodChannel setMethodCallHandler:nil];
//        methodChannel = nil;
    }
    
}


 NSString *authKey;
 NSString *privacyName;
 NSString *privacyUrl;
 NSString *userIssueName;
 NSString *userIssueUrl;
- (void)handleInitSdk:(FlutterMethodCall *)call result:(FlutterResult)result{
    NSDictionary *dict = call.arguments;
    NSString *authKey1;
    if([dict isKindOfClass:[NSDictionary class]]){
//        authKey = dict[@PARAM_AUTH_KEY];
        authKey1 = dict[@PARAM_AUTH_KEY];
    }
    NSLog(@"PhoneVerifyPlugin-->%@", privacyName);
    [[TXCommonHandler sharedInstance] setAuthSDKInfo:authKey1 complete:^(NSDictionary * _Nonnull resultDic) {
        
    }];
    
}
- (void)handleSetPrivacy:(FlutterMethodCall *)call result:(FlutterResult)result{
    NSDictionary *dict = call.arguments;
    
    if([dict isKindOfClass:[NSDictionary class]]){
        privacyName = dict[@PARAM_PRIVACY_ISSUE_NAME];
        privacyUrl = dict[@PARAM_PRIVACY_ISSUE_URL];
        userIssueName = dict[@PARAM_USER_ISSUE_NAME];
        userIssueUrl = dict[@PARAM_USER_ISSUE_URL];
    }
    result(@true);
    
}
- (void)handleCheckEnv:(FlutterMethodCall *)call result:(FlutterResult)result{
    [[TXCommonHandler sharedInstance] accelerateLoginPageWithTimeout:5.0 complete:^(NSDictionary * _Nonnull resultDic) {
        NSLog(@"accelerateVerifyWithTimeout---%@",resultDic);
//        __weak typeof(self) weakSelf = self;
//        [weakSelf showResult:resultDic result:result];
        if([PNSCodeSuccess isEqualToString:[resultDic objectForKey:@"resultCode"]]==YES){
            NSDictionary *dict = @{
                @"code": @"500000",
                @"message" : @"获取运营商成功",
//                    @"message" : [resultDic objectForKey:@"msg"],
                @"ISP" : [resultDic objectForKey:@"vendor"]?:@""
            };
            [methodChannel invokeMethod:@INVOKE_METHOD_ISP arguments:dict];
            result(@true);
            return;
        }
        if ([resultDic isKindOfClass:[NSString class]]) {
           
            NSDictionary *dict = @{
                @"code": @"500001",
                @"ISP" : resultDic,
                @"message" : @"获取运营商失败"
            };
            [methodChannel invokeMethod:@INVOKE_METHOD_ISP arguments:dict];
            result(@false);
        }
    }];
}
- (void)handleLogin:(FlutterMethodCall *)call result:(FlutterResult) result{
    
//    [self checkVerifyEnable:call result:result];
    
    TXCustomModel* model = [PNSBuildModelUtils buildFullScreenModel:privacyName
        privacyUrl:privacyUrl
        userIssueName:userIssueName
        userIssueUrl:userIssueUrl];
    
    model.supportedInterfaceOrientations = UIInterfaceOrientationMaskPortrait;
    [self startLoginWithModel: model call:call result:result complete:^{}];
}

- (void)handleQuit:(FlutterMethodCall *)call result:(FlutterResult) result{
    [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES  complete:nil];
    result(@true);
}

#pragma mark - action 一键登录公共方法
- (void)startLoginWithModel:(TXCustomModel *)model call:(FlutterMethodCall*)call result:(FlutterResult)result complete:(void (^)(void))completion {
    
    float timeout = 5.0; //self.tf_timeout.text.floatValue;
    __weak typeof(self) weakSelf = self;
    UIViewController *_vc = [self findCurrentViewController];
    
    

    //1.调用取号接口，加速授权页的弹起
    [[TXCommonHandler sharedInstance] accelerateLoginPageWithTimeout:timeout complete:^(NSDictionary * _Nonnull resultDic) {
        NSLog(@"PhoneVerifyPlugin-->%@",resultDic);
        if([PNSCodeSuccess isEqualToString:[resultDic objectForKey:@"resultCode"] ] == NO){
            NSDictionary *dict = @{
                @"code": @"500000",
                @"ISP" : resultDic,
                @"message" : @"获取运营商失败"
            };
            [methodChannel invokeMethod:@INVOKE_METHOD_ISP arguments:dict];
            result(@false);
            return;
        }
        //2. 调用获取登录Token接口，可以立马弹起授权页
        [[TXCommonHandler sharedInstance] getLoginTokenWithTimeout:timeout controller:_vc model:model complete:^(NSDictionary * _Nonnull resultDic) {
            NSString *code = [resultDic objectForKey:@"resultCode"];

             NSLog(@"foxlog resultDic: %@", resultDic);

            if ([PNSCodeSuccess isEqualToString:code]==YES) {
                //点击登录按钮获取登录Token成功回调
                // NSString *token = [resultDic objectForKey:@"token"];
                
                // NSLog( @"获取到token---->>>%@<<<-----", token );
                
                // NSLog( @"打印全部数据日志---->>>%@", resultDic );
              
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:nil];
//                    });
                NSDictionary *dict = @{
                    @"code": code,
                    @"message" : [resultDic objectForKey:@"msg"],
                    @"token" : [resultDic objectForKey:@"token"]?:@""
                };
                
                [methodChannel invokeMethod:@INVOKE_METHOD_LOGIN_TOKEN arguments:dict];
                result(@true);
            } else if ([PNSCodeLoginControllerClickCancel isEqualToString:code]) {
                NSDictionary *dict = @{
                    @"code": code,
                    @"message" : [resultDic objectForKey:@"msg"],
                    @"token" : [resultDic objectForKey:@"token"]?:@""
                };
                [methodChannel invokeMethod:@INVOKE_METHOD_ON_CLICK arguments:dict];
                result(@true);
            } else if ([PNSCodeLoginControllerClickChangeBtn isEqualToString:code]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:nil];
                });
                 NSDictionary *dict = @{
                     @"code": code,
                     @"message" : [resultDic objectForKey:@"msg"],
                     @"token" : [resultDic objectForKey:@"token"]?:@""
             };
                [methodChannel invokeMethod:@INVOKE_METHOD_ON_CLICK arguments:dict];
                result(@true);
             }
            [weakSelf showResult:resultDic result:result];
        }];
    }];

            
            
        
    
}

#pragma mark  ======在view上添加UIViewController========
- (UIViewController *)findCurrentViewController{
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    UIViewController *topViewController = [window rootViewController];
    while (true) {
        if (topViewController.presentedViewController) {
            topViewController = topViewController.presentedViewController;
        } else if ([topViewController isKindOfClass:[UINavigationController class]] && [(UINavigationController*)topViewController topViewController]) {
            topViewController = [(UINavigationController *)topViewController topViewController];
        } else if ([topViewController isKindOfClass:[UITabBarController class]]) {
            UITabBarController *tab = (UITabBarController *)topViewController;
            topViewController = tab.selectedViewController;
        } else {
            break;
        }
    }
    return topViewController;
}

#pragma mark -  格式化数据utils
- (void)showResult:(id __nullable)showResult result:(FlutterResult)result  {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *desc = nil;
        if ([showResult isKindOfClass:NSString.class]) {
            desc = (NSString *)showResult;
        } else {
            desc = [showResult description];
            // if (desc != nil) {
            //     desc = [NSString stringWithCString:[desc cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding];
            // }
        }
        NSLog( @"flutter打印日志---->>%@", desc );
    });
}
@end
